package com.weihua.ws;

import com.weihua.bo.MachineBo;
import com.weihua.modbus.IView;
import com.weihua.modbus.ViewModal;
import com.weihua.service.MachineService;
import com.weihua.service.ModbusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/plc/{id}")
public class MonitorServer {
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    private static Map<String, IView> sessionViews = new ConcurrentHashMap<>();

    @Autowired
    private MachineService machineService;

    @Autowired
    private ModbusService modbusService;

    @OnOpen
    public void open(Session session, @PathParam(value = "id")String id){
        log.info("websocket 链接机器：{}", id);
        if (id!=null && !"".equals(id)){
            MachineBo bo = machineService.getById(id);
            if (bo!=null){
                IView view = new ViewModal();
                view.setParam(bo);
                view.setSessionKey(session.getId());
                sessionMap.put(session.getId(), session);
                sessionViews.put(session.getId(), view);
                modbusService.addView(session.getId(), view);
                modbusService.addMonitor(bo);
            }
        }
    }


    @OnClose
    public void onClose(Session session){
        modbusService.removeView(sessionViews.get(session.getId()));
        sessionViews.remove(session.getId());
        sessionMap.remove(session.getId());
    }

    public static void sendAll(String msg, String sessionKey){
        if(StringUtils.hasText(sessionKey)){
            sendMessage(msg, sessionMap.get(sessionKey));
        }
    }

    private static void sendMessage(String msg, Session session) {
        if (session!= null){
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                log.warn("发送数据失败:{}",e.getMessage());
            }
        }
    }
}
